<?php
namespace frontend\controllers;

use yii\web\Controller;
use frontend\models\MatchMsg;
use frontend\models\MatchImg;
use frontend\models\MatchImgId;
use frontend\models\MatchType;
use Yii;
use yii\helpers\Url;
use yii\web\UploadedFile;
use frontend\models\User;

class MatchController extends Controller
{

    public function actionIndex()
    {
        $this->layout = 'match';
        return $this->render('index');
    }

    public function actionDetail()
    {
        $this->layout = 'match';
        return $this->render('detail');
    }

    public function actionSort()
    {
        $this->layout = 'match';
        return $this->render('sort');
    }

    public function actionCooperation()
    {
        $this->layout = 'match';
        return $this->render('cooperation');
    }

    public function actionDownload()
    {
        $this->layout = 'match';
        $filename = Yii::$app->request->get('filename');
        $basepath = Yii::$app->basePath;
        if (!empty(Yii::$app->request->get('filename'))){
            $filename = Yii::$app->request->get('filename');
            $name = [
                '1.pdf' => '初评A4参赛作品格式.pdf',
                '2.pdf' => '终评A0展板格式.pdf',
                '3.jpg' => '产品类参赛作品版式参考.jpg',
                '4.pdf' => '大赛介绍PDF.pdf'
            ];
            $file_name = basename($filename);
            $file_dir  = dirname($filename);
            $file = fopen($basepath.'/web/'.$filename,"r"); 
            Header("Content-type:application/pdf");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length: ".filesize($basepath.'/web/'.$filename));
            $ua = $_SERVER["HTTP_USER_AGENT"];
            if (preg_match('/MSIE/', $ua)) {
                header('Content-Disposition: attachment; filename="'.urlencode($name[$file_name]) . '"');
            } elseif (preg_match("/Firefox/", $ua)) {
                header('Content-Disposition: attachment; filename*="utf8\'\''.$name[$file_name].'"');
            } else {
                header('Content-Disposition: attachment; filename="'.$name[$file_name].'"');
            }
            //Header("Content-Disposition: attachment; filename=" .rawurlencode($name[$file_name])); 
            ob_clean();
            flush();
            echo fread($file,filesize($basepath.'/web/'.$filename));
            fclose($file);
        }
        return $this->render('download');
    }

    public function actionShow()
    {
        $this->layout = 'match';
        return $this->render('show');
    }

    public function actionUpload()
    {
        $this->layout = 'match';
        $model = new MatchImg();
        if (Yii::$app->user->isGuest) {
            return $this->redirect(['site/login']);
        } else {
            $applyed = MatchMsg::findOne(['uid' => Yii::$app->user->identity->id]); // 获取基本信息
            if (! empty($applyed)) {
                $model = MatchImg::find()->where(['uid'=>Yii::$app->user->identity->id])->asArray()->all();
                foreach ($model as $key=>$item){
                    $num = count(MatchImgId::findAll(['uid'=>Yii::$app->user->identity->id,'img_id'=>$item['id']])); 
                    $typeContent = MatchType::find()->select(['CONCAT(type," ", type_value)'])->where(['type'=>$item['type']])->column();
                    $model[$key]['num'] = $num;
                    $model[$key]['typeContent'] = $typeContent[0];
                }
                $numImg = count(MatchImg::findAll(['uid'=>Yii::$app->user->identity->id]));
                return $this->render('upload', [
                    'model' => $model,
                    'numImg' => $numImg
                ]);
            } else {
                $model = new MatchMsg();
                return $this->render('uploadMsg', [
                    'model' => $model
                ]);
            }
        }
    }
    /*
     * 修改作品
     *  */
    public function actionUpdate()
    {
        if(Yii::$app->request->get('id')){
            $model = new MatchImg();
            $getId = Yii::$app->request->get('id');
            $five = MatchType::find()->select(['CONCAT(type," ", type_value)','type'])->indexBy('type')->column();
            return $this->render('uploadImg',[
                'modifyId' => $getId,
                'model' => $model,
                'five' => $five
            ]);
        }else{
            echo "未获取修改图片的id";
            return;
        }
    }
    

    /*
     * 上传作品表单
     */
    public function actionUploadImg()
    {
        $this->layout = 'match';        
        $model = new MatchImg();
        $five = MatchType::find()->select(['CONCAT(type," ", type_value)','type'])->indexBy('type')->column();
        if (Yii::$app->request->isPost) {
            //如果是有id参数则是修改
            if(!empty(Yii::$app->request->get('id'))){
                $modifyId = Yii::$app->request->get('id');
                $model = MatchImg::findOne(['id'=>$modifyId]);
                $model -> deleteSame();//删文件
                MatchImgId::deleteAll(['img_id'=>$modifyId]);//删数据库
            }
            $model->uid = Yii::$app->user->identity->id;
            if ($model->load(Yii::$app->request->post())) {
                $model->img = UploadedFile::getInstances($model, 'img');  //模型赋予 图片实例
                $model->imgs = UploadedFile::getInstances($model, 'imgs');
                if ($model->validate()) {
                    $model->up_time = time();
                    $model->save();
                }else {
                    return $this->render('submitSuccess', [
                        'status' => 'warning',
                        'redirectUrl' => Url::to(['match/upload-img']),
                        'msg' => "验证失败"
                    ]);
                }
                
                if ($model->upload()){
                    return $this->render('submitSuccess', [
                        'status' => 'success', 
                        'redirectUrl' => Url::to(['match/upload']),
                        'msg' => "提交成功，正在跳转……"
                    ]);
                }else {
                    return $this->render('submitSuccess', [
                        'status' => 'warning',
                        'redirectUrl' => Url::to(['match/upload-img' ]),
                        'msg' => "上传失败"
                    ]);
                }
            } else {
                return $this->render('submitSuccess', [
                    'status' => 'error',
                    'redirectUrl' => Url::to(['match/upload-img']),
                    'msg' => "写入失败"
                ]);
            }
        } else {
            return $this->render('uploadImg', [
                'model' => $model,
                'five' => $five
            ]);
        }
    }

    /*
     * 上传基本信息表单
     */
    public function actionUploadMsg()
    {
        $this->layout = 'match';
        $model = new MatchMsg();
        if (Yii::$app->request->isPost) {
            if ($model->load(Yii::$app->request->post()) && $model->validate()) {
                $uid = Yii::$app->user->identity->id;
                $added = MatchMsg::findOne(['uid' => $uid]);
                if (!empty($added)){
                    $added->delete();
                }
                $model->uid = $uid ;
                $model->save();
                return $this->render('submitSuccess', [
                    'status' => 'success',
                    'redirectUrl' => Url::to(['match/upload']),
                    'msg' => "提交成功，正在跳转……"
                ]);
            } else {
                return $this->render('submitSuccess', [
                    'status' => 'error',
                    'redirectUrl' => Url::to([
                        'match/upload-msg'
                    ]),
                    'msg' => "写入失败"
                ]);
            }
        } else {
            $model = MatchMsg::findOne(['uid'=>Yii::$app->user->identity->id]);
            return $this->render('uploadMsg', [
                'model' => $model
            ]);
        }
    }
}    
